package com.mongodb.dao;

import com.mongodb.entity.User;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Repository;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author Conceit
 * @version 1.0, 2017/1/9
 */
@Repository(value = "userDaoImpl")
public class UserDaoImpl implements IUserDao {
    @Resource
    MongoTemplate mongoTemplate;

    public List<User> findByEmail(String email) {
        Query query = new Query();
        query.addCriteria(Criteria.where("email").is(email));
        return mongoTemplate.find(query, User.class);
    }

    public User findOneByUserId(String userId) {
        Query query = new Query();
        User user = mongoTemplate.findOne(query.addCriteria(Criteria.where("userId").is(userId)), User.class);
        return user;
    }

    public void saveUser(User user) {

        mongoTemplate.save(user);
    }

    //查找相似的用户名返回的是用户list
    public List<User> findAllUserByName(String name) {
        //模糊匹配
        //Pattern pattern = Pattern.compile("^.*\"+name+\".*$", Pattern.CASE_INSENSITIVE);
        // Query query= new Query(Criteria.where("nameName").regex(name,"i"));
        Query query = new Query();
        Criteria cr = new Criteria();
        query.addCriteria(cr.orOperator(Criteria.where("userName").regex(name)));
        List<User> userList = mongoTemplate.find(query, User.class);
        return userList;
    }

    // /根据时间区间 获取所有的用户数据列表
    public List<User> findUsersByTime(Date startTime, Date endTime) {
        Query query = new Query();
        Criteria cr = new Criteria();
        query.addCriteria(cr.where("birthday").gte(startTime).lte(endTime));
        List<User> userList = mongoTemplate.find(query, User.class);
        return userList;
    }
}
